package com.jic.member.impl.power;
import	java.util.ArrayList;
import java.util.Date;
import	java.util.List;
import java.lang.Long;
import java.util.stream.Collectors;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.request.MerchantRequest;
import com.jic.manager.request.MestoreRequest;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.MerchantResponse;
import com.jic.manager.response.SysDeptResponse;
import com.jic.member.common.util.BeanUtil;
import com.jic.member.entity.power.MepowerProduct;
import com.jic.member.entity.power.MepowerStore;
import com.jic.member.entity.power.Meproduct;
import com.jic.member.enums.TypeOfProductEnum;
import com.jic.member.mapper.power.MepowerProductMapper;
import com.jic.member.mapper.power.MepowerStoreMapper;
import com.jic.member.mapper.power.MeproductMapper;
import com.jic.member.request.power.MepowerProductRequest;
import com.jic.member.request.power.ProductSaveBatchRequest;
import com.jic.member.response.power.MeproductResponse;
import com.jic.member.service.power.MepowerProductService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 权益商品关联表
 * @author : zxl
 * @email :
 * @since : 2020-05-11 02:45:38
 * @version : v1.0.0
 */
@Service
public class MepowerProductServiceImpl implements MepowerProductService{

    @Resource
    private MepowerProductMapper mepowerProductMapper;
    @Resource
    private MepowerStoreMapper mepowerStoreMapper;
    @Resource
    private MeproductMapper meproductMapper;
    @Resource
    private ManagerMerchantApi managerMerchantApi;
    @Resource
    private ManagerStoreApi managerStoreApi;
    @Resource
    private ProductListApi productListApi;
    @Resource
    private MepowerProductService mepowerProductService;
    @Resource
    private SysDeptApi sysDeptApi;

    @Override
    public long insert(MepowerProduct mepowerProduct) {
        long flag = mepowerProductMapper.insert(mepowerProduct);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return mepowerProductMapper.delete(id);
    }

    @Override
    public long update(MepowerProduct mepowerProduct) {
        return mepowerProductMapper.update(mepowerProduct);
    }

    @Override
    public MepowerProduct queryByPrimaryKey(Long id){
        return mepowerProductMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<MepowerProduct> query(MepowerProduct mepowerProduct){
        return mepowerProductMapper.query(mepowerProduct);
    }

    @Override
    public PageResult<MepowerProduct> queryPage(MepowerProduct mepowerProduct, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        //查询关联表 mem_power_product
        MepowerProduct powerProduct = new MepowerProduct(){{
            setLegalRuleId(mepowerProduct.getLegalRuleId());
        }};
        List<MepowerProduct> powerResult = mepowerProductMapper.query(powerProduct);
        mepowerProduct.setPowerProductId(powerResult.size() == 1? powerResult.get(0).getId().longValue() : null);
        mepowerProduct.setMpParentId(0L);
        List<MepowerProduct> list = mepowerProductMapper.queryPage(startIndex, pageQuery.getLimit(), mepowerProduct);
        long count = mepowerProductMapper.queryPageCount(mepowerProduct);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getMpParentId() == 0) {
                mepowerProduct.setMpParentId(list.get(i).getMpId());
                mepowerProduct.setPowerProductId(list.get(i).getPowerProductId());
                mepowerProduct.setDeleteFlag(0);
                List<MepowerProduct> resultList = mepowerProductMapper.querySku(mepowerProduct);
                List<MeproductResponse> skuList = resultList.stream().map(temp -> {
                    MeproductResponse memberResponse = BeanUtil.copy(temp, MeproductResponse.class);
                    return memberResponse;
                }).filter(item -> item != null).collect(Collectors.toList());
                list.get(i).setChildren(skuList);
            }
        }

        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public List<Long> queryStoreIds(MepowerProductRequest form) {
        List<Long> ids =new ArrayList<> ();
        MepowerStore mepowerStoreRequest = new MepowerStore(){{
            setLegalRuleId(form.getLegalRuleId());
            setDeleteFlag(0);
        }};
        List<MepowerStore> mepowerProducts = mepowerStoreMapper.query(mepowerStoreRequest);
        mepowerProducts.forEach(item -> {
            ids.add(item.getStoreId());
        });
        return ids;
    }

    @Override
    public Long saveProduct(MepowerProductRequest request) {
        MepowerProduct query = new MepowerProduct();
        MepowerProduct mepower = new MepowerProduct();
        query.setLegalRuleId(request.getLegalRuleId());
        List<MepowerProduct> resultList = mepowerProductMapper.query(query);
        if(CollectionUtils.isEmpty(resultList)){
            //插入mem_power_product
            mepower.setLegalRuleId(request.getLegalRuleId());
            mepower.setDeleteFlag(0);
            mepower.setStatus(1);
            mepower.setCreateTime(new Date());
            mepowerProductMapper.insert(mepower);
        }
        List<ProductSaveBatchRequest> batchSpuRequestList = request.getProductList();
        if(CollectionUtils.isEmpty(batchSpuRequestList)){
            return null;
        }
        List<Long> spuIds = batchSpuRequestList.stream().map(ProductSaveBatchRequest::getSpuId).collect(Collectors.toList());
        GoodsPageQueryRequest goodsSkuQueryRequest = new GoodsPageQueryRequest();
        goodsSkuQueryRequest.setSpuIds(spuIds);
        //根据spuIds 查询出sku
        List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuId(goodsSkuQueryRequest);

        if(CollectionUtils.isEmpty(productStoreInfos)){
            return null;
        }
        Long PowerProductId = mepower.getId() != null? mepower.getId(): resultList.get(0).getId().longValue();
        for(int i = 0; i < productStoreInfos.size(); i++){
            ProductStoreInfo goodsSpuInfo = productStoreInfos.get(i);
            Meproduct queryEntity = new Meproduct();
            queryEntity.setMpId(goodsSpuInfo.getId());
            queryEntity.setDeleteFlag(0);
            queryEntity.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            queryEntity.setPowerProductId(PowerProductId);
            //查询spu是否重复
            List<Meproduct> spuList = meproductMapper.query(queryEntity);
            if(CollectionUtils.isNotEmpty(spuList)){
                 continue;
            }
            Meproduct entitySpu = new Meproduct();
            entitySpu.setPowerProductId(PowerProductId);
            entitySpu.setMpId(goodsSpuInfo.getId());
            entitySpu.setMpName(goodsSpuInfo.getChineseName());
            entitySpu.setMpParentId(0L);
            entitySpu.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            entitySpu.setCategoryName(goodsSpuInfo.getCategoryName());
//            entitySpu.setStoreId(goodsSpuInfo.getStoreId());
//            entitySpu.setMerchantId(goodsSpuInfo.getMerchantId());
//            entitySpu.setMerchantName(getMerchanName(goodsSpuInfo.getMerchantId()));
            entitySpu.setCreateTime(new Date());
            entitySpu.setCreator(request.getCreator());
            entitySpu.setDeleteFlag(0);
            entitySpu.setStoreName(goodsSpuInfo.getStoreName());
            entitySpu.setMpCode(goodsSpuInfo.getCode());
            entitySpu.setSalePrice(goodsSpuInfo.getSalePriceWithTax().toString());
            meproductMapper.insert(entitySpu);
            //插入sku
            List<ProductStoreInfo> goodsSkuInfoList = productStoreInfos.get(i).getChildren();
            if (CollectionUtils.isNotEmpty(goodsSkuInfoList)){
                goodsSkuInfoList.forEach(goodsSkuInfo -> {
                    Meproduct entitysKu = new Meproduct();
                    entitysKu.setPowerProductId(PowerProductId);
                    entitysKu.setMpId(goodsSpuInfo.getId());
                    entitysKu.setMpParentId(0L);
                    entitysKu.setMpName(goodsSpuInfo.getChineseName());
                    entitysKu.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
                    entitysKu.setMpCode(goodsSkuInfo.getCode());
                    entitysKu.setCategoryName(goodsSpuInfo.getCategoryName());
                    entitysKu.setCreator(request.getCreator());
                    entitysKu.setUpdator(request.getUpdator());
                    entitysKu.setMpId(goodsSkuInfo.getId());
                    entitysKu.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                    entitysKu.setMpParentId(goodsSpuInfo.getId());
//                    entitysKu.setMerchantId(goodsSkuInfo.getMerchantId());
//                    entitysKu.setStoreId(goodsSkuInfo.getStoreId());
                    entitysKu.setCreator(request.getCreator());
                    entitysKu.setCreateTime(new Date());
//                    entitysKu.setMerchantName(getMerchanName(goodsSkuInfo.getMerchantId()));
                    entitysKu.setStoreName(getStoreName(goodsSkuInfo.getDeptId()));
                    entitysKu.setDeleteFlag(0);
                    entitysKu.setSalePrice(goodsSkuInfo.getSalePriceWithTax().toString());
                    meproductMapper.insert(entitysKu);
                });
            }

        }
        return 0L;
    }

    @Override
    public RestResult querySpuPage(MepowerProductRequest form) {
        RestResult result = new RestResult();
        GoodsPageQueryRequest request = new GoodsPageQueryRequest();
        List<Long> storeIds = mepowerProductService.queryStoreIds(form);
        request.setStoreIds(storeIds);
        request.setStart(form.getStart());
        request.setLimit(form.getLimit());
        request.setGoodsName(form.getGoodsName());
        request.setGoodsCategory(form.getGoodsCategory());
        List<Long>merchantIds = new ArrayList<> ();
        List<Long>stores = new ArrayList<> ();
        if (null != form.getMerchantName() && form.getMerchantName() !=""){
            MerchantRequest merchantName = new MerchantRequest();
            merchantName.setName(form.getMerchantName());
            List<MerchantResponse> query = managerMerchantApi.query(merchantName);
            if(CollectionUtils.isEmpty(query)){
                merchantIds.add(0L);
            }
            query.forEach(item->{
                merchantIds.add(item.getId());
            });
        }
       // request.setMerchantIds(merchantIds);
        if (null != form.getStoreName() && form.getStoreName() !=""){
            MestoreRequest mestore = new MestoreRequest();
            mestore.setStoreName(form.getStoreName());
            List<MemStoreResponse> resultStore = managerStoreApi.getStoreInfoList(mestore);
            if(CollectionUtils.isEmpty(resultStore)){
                stores.add(0L);
            }
            resultStore.forEach(item->{
                stores.add(item.getId());
            });
        }
        if (CollectionUtils.isEmpty(storeIds)){
            result.setCode("9999");
            result.setMsg("请先添加店铺！");
            return result;
        }
        request.setTypeOfProduct(1);
        RestResult<PageResult<ProductStoreInfo>> pageResultRestResult = productListApi.queryProductPageByStoreId(request);
        return RestResult.success(pageResultRestResult);
    }

    @Override
    public void deletePowerProduct(MepowerProductRequest form) {
        if (null  != form){
            //如果mpParentId为0 则为spu
            if (form.getMpParentId() == 0) {
                Meproduct meproduct = meproductMapper.queryByPrimaryKey(form.getId().longValue());
                meproductMapper.delete(form.getId().longValue());
                if (null != meproduct) {
                    Meproduct product= new Meproduct();
                    product.setPowerProductId(meproduct.getPowerProductId());
                    product.setMpParentId(meproduct.getMpId());
                    List<Meproduct> productList = meproductMapper.query(product);
                    productList.forEach(itme->{
                        meproductMapper.delete(itme.getId().longValue());
                    });
                }
            }else {
                meproductMapper.delete(form.getId().longValue());
            }
        }

    }

    @Override
    public void deletePowerProductsByBatch(MepowerProductRequest form) {
        if (null != form){
            form.getProductDelete().forEach(itmes->{
                if (itmes.getMpParentId() == 0) {
                    Meproduct meproduct = meproductMapper.queryByPrimaryKey(itmes.getId().longValue());
                    meproductMapper.delete(itmes.getId().longValue());
                    if (null != meproduct) {
                        Meproduct product= new Meproduct();
                        product.setPowerProductId(meproduct.getPowerProductId());
                        product.setMpParentId(meproduct.getMpId());
                        List<Meproduct> productList = meproductMapper.query(product);
                        productList.forEach(info->{
                            meproductMapper.delete(info.getId().longValue());
                        });
                    }
                }else {
                    meproductMapper.delete(itmes.getId().longValue());
                }
            });
        }

    }

    @Override
    public Long addAllProduct(MepowerProductRequest request) {
        //查询出当前权益下的所有店铺信息
        MepowerProductRequest mepowerStoreRequest = new MepowerProductRequest(){{
            setLegalRuleId(request.getLegalRuleId());
            setDeleteFlag(0);
        }};
        List<Long> storeList = this.queryStoreIds(mepowerStoreRequest);
        if (CollectionUtils.isEmpty(storeList)){
            return null;
        }
        GoodsPageQueryRequest goods= new GoodsPageQueryRequest();
        goods.setStoreIds(storeList);
        goods.setStart(1);
        goods.setLimit(1000000);
        //获取所有商品spu信息
        RestResult<PageResult<ProductStoreInfo>> restResult = productListApi.queryProductPageByStoreId(goods);
        MepowerProduct query = new MepowerProduct();
        MepowerProduct mepower = new MepowerProduct();
        query.setLegalRuleId(request.getLegalRuleId());
        //查询mem_power_product是否存在信息
        List<MepowerProduct> resultList = mepowerProductMapper.query(query);
        if(CollectionUtils.isEmpty(resultList)){
            //插入mem_power_product
            mepower.setLegalRuleId(request.getLegalRuleId());
            mepower.setDeleteFlag(0);
            mepower.setStatus(1);
            mepower.setCreateTime(new Date());
            mepowerProductMapper.insert(mepower);
        }
        List<Long> spuIds = new ArrayList<>();
        restResult.getData().getRows().forEach(itme->{
            spuIds.add(itme.getId());
        });
        GoodsPageQueryRequest goodsSkuQueryRequest = new GoodsPageQueryRequest();
        goodsSkuQueryRequest.setSpuIds(spuIds);
        //根据spuIds 查询出sku
        List<ProductStoreInfo> goodsInfoResponseList = productListApi.queryProductBySpuId(goodsSkuQueryRequest);

        if(CollectionUtils.isEmpty(goodsInfoResponseList)){
            return null;
        }
        Long PowerProductId = mepower.getId() != null? mepower.getId(): resultList.get(0).getId().longValue();
        for(int i = 0; i < goodsInfoResponseList.size(); i++){
            ProductStoreInfo goodsSpuInfo = goodsInfoResponseList.get(i);
            Meproduct queryEntity = new Meproduct();
            queryEntity.setMpId(goodsSpuInfo.getId());
            queryEntity.setDeleteFlag(0);
            queryEntity.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            queryEntity.setPowerProductId(PowerProductId);
            //查询spu是否重复
            List<Meproduct> spuList = meproductMapper.query(queryEntity);
            if(CollectionUtils.isNotEmpty(spuList)){
                continue;
            }
            Meproduct entitySpu = new Meproduct();
            entitySpu.setPowerProductId(PowerProductId);
            entitySpu.setMpId(goodsSpuInfo.getId());
            entitySpu.setMpName(goodsSpuInfo.getChineseName());
            entitySpu.setMpParentId(0L);
            entitySpu.setSalePrice(goodsSpuInfo.getSalePriceWithTax().toString());
            entitySpu.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
            entitySpu.setCategoryName(goodsSpuInfo.getCategoryName());
//            entitySpu.setStoreId(goodsSpuInfo.getStoreId());
//            entitySpu.setMerchantId(goodsSpuInfo.getMerchantId());
//            entitySpu.setMerchantName(getMerchanName(goodsSpuInfo.getMerchantId()));
            entitySpu.setStoreName(goodsSpuInfo.getStoreName());
            entitySpu.setCreateTime(new Date());
            entitySpu.setCreator(request.getCreator());
            entitySpu.setDeleteFlag(0);
            entitySpu.setMpCode(goodsSpuInfo.getCode());
            meproductMapper.insert(entitySpu);
            //插入sku
            List<ProductStoreInfo> goodsSkuInfoList = goodsInfoResponseList.get(i).getChildren();
            if (CollectionUtils.isEmpty(goodsSkuInfoList)){
                continue;
            }
            goodsSkuInfoList.forEach(goodsSkuInfo -> {
                Meproduct entitysKu = new Meproduct();
                entitysKu.setPowerProductId(PowerProductId);
                entitysKu.setMpId(goodsSpuInfo.getId());
                entitysKu.setMpParentId(0L);
                //entitysKu.setSalePrice(String.valueOf(goodsSkuInfo.getSalePrice()));
                entitysKu.setMpName(goodsSpuInfo.getChineseName());
                entitysKu.setTypeOfProduct(TypeOfProductEnum.GOODS_SPU.getCode());
                entitysKu.setMpCode(goodsSkuInfo.getCode());
                entitysKu.setCategoryName(goodsSpuInfo.getCategoryName());
                entitysKu.setCreator(request.getCreator());
                entitysKu.setUpdator(request.getUpdator());
                entitysKu.setMpId(goodsSkuInfo.getId());
                entitysKu.setTypeOfProduct(TypeOfProductEnum.GOODS_SKU.getCode());
                entitysKu.setMpParentId(goodsSpuInfo.getId());
//                entitysKu.setMerchantId(goodsSkuInfo.getMerchantId());
//                entitysKu.setStoreId(goodsSkuInfo.getStoreId());
                entitysKu.setCreator(request.getCreator());
                entitysKu.setCreateTime(new Date());
//                entitysKu.setMerchantName(getMerchanName(goodsSkuInfo.getMerchantId()));
                entitysKu.setStoreName(getStoreName(goodsSkuInfo.getDeptId()));
                entitysKu.setDeleteFlag(0);
                meproductMapper.insert(entitysKu);
            });
        }

        return 0L;
    }

    private String getMerchanName(Long merchantId){
        List<Long> merchantList = new ArrayList<>();
        merchantList.add(merchantId);
        RestResult<List<MerchantRequest>> resultList = managerMerchantApi.queryMerchantListByid(merchantList);
        if(null != resultList && null != resultList.getData() && !resultList.getData().isEmpty()){
            return resultList.getData().get(0).getName();
        }
        return null;
    }

    private String getStoreName(Long storeId){
        SysDeptRequest sysDept =new SysDeptRequest();
        sysDept.setId(storeId);
        List<SysDeptResponse> result = sysDeptApi.query(sysDept);
        if(null != result){
            return result.get(0).getDeptName();
        }
        return null;
    }

}
